package com.bullsora.kindlerss.business.mail;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * @author sorin.buliarca@iquesint.com
 */
@Component
public class KindleMailSender {

  public static final Log LOG = LogFactory.getLog(KindleMailSender.class);

  private static final String KINDLE_ACCOUNT_SUFFIX = "@free.kindle.com";

  @Value("${email.username}")
  private String from;

  @Autowired
  private JavaMailSender mailSender;

  public void sendMessage(String htmlToSend, String fileName, String kindleAccount) {
    LOG.info(String.format("Sending mail with attachment: [%1$s]: %2$s", fileName, htmlToSend));

    try {
      MimeMessage message = mailSender.createMimeMessage();
      
      MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
      messageHelper.setTo(kindleAccount + KINDLE_ACCOUNT_SUFFIX);
      messageHelper.setFrom(from);
      messageHelper.setSubject("feed");
      messageHelper.setText("feed");
      
      messageHelper.addAttachment(fileName, new ByteArrayResource(htmlToSend.getBytes()));

      mailSender.send(message);
    } catch (Exception e) {
      LOG.error("Error while sending mail", e);
      throw new MailException(e);
    }
  }


  public String getFrom() {
    return from;
  }

  public void setFrom(String from) {
    this.from = from;
  }

}
